import Link from 'next/link'
import { useState } from 'react';
import { prepareConnection } from 'db/index'
import { formatDistanceToNowStrict,format} from 'date-fns'
import { observer } from "mobx-react-lite";
import MarkDown from 'markdown-to-jsx'
import { useStore } from 'store/index'
import { Article } from "@/db/entity";
import { IArticle } from '../api';
import { Avatar, Input,Button,message, Divider} from 'antd'
import request from 'service/fetch'
import styles from './index.module.scss'

interface IProps {
  article: IArticle;
}

export async function getServerSideProps({params}: {params: {id: string}}) {
  const articleId = params?.id;
    const db = await prepareConnection()
    const articleRepo = db.getRepository(Article)
    const article = await db.getRepository(Article).findOne({
      where: { id: articleId },
      relations:["user",'comments','comments.user'],
    })
    // 阅读量加一
    if (article) {
      article.views = article?.views + 1 ;
      await articleRepo.save(article)
    }
    return {
      props: {
        article: JSON.parse(JSON.stringify(article)) 
      },
    };
  }

const ArticleDetail = (props:IProps) => {
  const { article } = props;
  console.log(article)
  const {user:{nickname,avatar,id}} = article;
  // state
  const store = useStore()
  const loginUserInfo = store.user.userInfo;
  // data
  const [inputVal, setInputVal] = useState('')
  const [comments, setComments] = useState(article?.comments || [])
    
  // 发表评论
  const handleComment = () => {
    request.post('/api/comment/publish', {content: inputVal,articleId: article?.id}).then((res:any)=>{
      if(res?.code === 0){
        message.success('评论成功')
        setInputVal('')
        const newComments = [...comments,res?.data]
        setComments(newComments)
      }else{
        message.error('评论失败')
      }
    })
  }
  
  return (
    <div>
      <div className='content-layout'>
        <h2 className={styles.title}></h2>
        <div className={styles.user}>
          <Avatar src={avatar} size={50}></Avatar>
          <div className={styles.info}>
            <div className={styles.name}>{nickname}</div>
            <div className={styles.date}>
              <div>{formatDistanceToNowStrict(new Date(article?.update_time))}</div>
              <div>阅读 {article?.views}</div>
              {
                Number(loginUserInfo?.userId) === Number(id) && (
                  <Link href={`/editor/${article?.id}`}>编辑</Link>
                )
              }
            </div>
          </div>

        </div>
        <MarkDown className={styles.markdown}>{article?.content}</MarkDown>
      </div>
      <div className={styles.divider}></div>
      <div className='content-layout'>
        <div className={styles.comment}>
          <h3>评论 {comments.length}</h3>
          {
            loginUserInfo?.userId && (
              <div className={styles.enter}>
                <Avatar src={avatar} size={50}></Avatar>
                <div className={styles.content}>
                  <Input.TextArea rows={4} placeholder='请输入评论内容' value={inputVal} onChange={
                    (event)=> setInputVal(event?.target.value)
                    }
                  />
                  <Button type='primary' onClick={handleComment}>发表评论</Button>
                </div>
              </div>
            )
          }
          <Divider></Divider>
          <div className={styles.display}>
            {
              comments?.map((item:any) => {
              return (
                  <div className={styles.wrapper} key={item?.id}>
                    <Avatar src={item?.user?.avatar} size={40}></Avatar>  
                    <div className={styles.info}>
                      <div className={styles.name}>
                        <div>{item?.user.nickname}</div>
                        <div className={styles.date}>{format(new Date(item?.update_time),'yyyy-MM-dd hh:mm:ss')}</div>
                      </div>
                      <div className={styles.content}>{item?.content}</div>
                    </div>
                  </div>
                ) 
              })
            }
          </div>
        </div>
      </div>
    </div>
  );
};

export default observer(ArticleDetail);